<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isNew ? '新建单位/科室' : '修改单位/科室'"
    width="600px"
    :before-close="close"
    :close-on-click-modal="false"
  >
    <div v-loading="loading">
      <el-form ref="formRef" :model="formData" label-width="100" :rules="rules">
        <el-form-item label="简称：" prop="unitForShort">
          <el-input v-model="formData.unitForShort" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="全称：" prop="unitAllName">
          <el-input v-model="formData.unitAllName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="顺序：" prop="sort">
          <el-input-number v-model="formData.sort" :min="1" />
        </el-form-item>
        <el-form-item label="类型：" prop="unitType">
          <el-select
            v-model="formData.unitType"
            :disabled="!isNew || unitTypeDisabled"
            placeholder="请选择"
            @change="handleChangeType"
          >
            <el-option label="单位" value="1" />
            <el-option label="科室" value="2" />
          </el-select>
        </el-form-item>
        <template v-if="formData.unitType === '2'">
          <el-form-item label="父级：" prop="parentId">
            <el-select
              v-model="formData.parentId"
              :disabled="!isNew || haveParentName"
            >
              <el-option
                v-for="item of unitStore.list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </template>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submit" :loading="loading">
          提交
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { reactive, ref, useTemplateRef } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { addOrUpdateUnit } from '@/api/sys/unit'
import useUnitStore from '@/stores/unit'

const unitStore = useUnitStore()

const formRef = useTemplateRef<FormInstance>('formRef')

const emit = defineEmits(['update'])

const dialogVisible = ref(false)
const isNew = ref(true)
const haveParentName = ref(false)
const loading = ref(false)
const unitTypeDisabled = ref(false)

const formData = reactive({
  id: undefined,
  unitForShort: undefined,
  unitAllName: undefined,
  sort: 1,
  unitType: '1',
  parentId: 0,
})

const rules = reactive<FormRules<typeof formData>>({
  unitForShort: [
    { required: true, message: '请输入单位/科室名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
  ],
  unitAllName: [
    { required: true, message: '请输入单位/科室名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
  ],
  unitType: { required: true, message: '请选择类型', trigger: 'change' },
  sort: { required: true, message: '请输入大于 0 的顺序值', trigger: 'change' },
  parentId: { required: true, message: '请选择父级', trigger: 'change' },
})

function handleChangeType() {
  formData.parentId = null
}

defineExpose({ show })

function show(row?: any, parentId?: number) {
  dialogVisible.value = true
  if (row) {
    formData.id = row.id
    formData.unitForShort = row.unitForShort
    formData.unitAllName = row.unitAllName
    formData.sort = row.sort
    formData.unitType = row.unitType
    formData.parentId = row.parentId
    isNew.value = false
  }
  if (parentId || parentId === 0) {
    formData.parentId = parentId
    formData.unitType = '2'
    unitTypeDisabled.value = true
    haveParentName.value = true
  }
}

function close() {
  dialogVisible.value = false
  isNew.value = true
  haveParentName.value = false
  loading.value = false
  unitTypeDisabled.value = false
  formRef.value.resetFields()
  Object.assign(formData, {
    id: undefined,
    unitForShort: undefined,
    unitAllName: undefined,
    sort: 1,
    unitType: '1',
    parentId: 0,
  })
}

async function submit() {
  const bool = await formRef.value.validate()
  if (!bool) {
    return
  }
  loading.value = true
  const postData = {
    ...formData,
  }
  const { data } = await addOrUpdateUnit(postData)
  if (data.status === 200) {
    ElMessage.success(data.message)
  }
  loading.value = false
  emit('update')
  close()
}
</script>
<style scoped lang="scss"></style>
